package 字串;

import java.util.HashMap;

/**
 * @author TTDB
 * @create 2025/9/13
 */
public class subarraySum {
     public int subarraySum(int[] nums, int k)
    {
        //使用前缀和来做
        int[] preSum = new int[nums.length + 1];
        preSum[0] = 0;
        for (int i = 1; i <= nums.length; i++) {
            preSum[i] = preSum[i - 1] + nums[i - 1];
        }
        int count = 0;
        //和为k的子数组，一次遍历如果当前前缀和减去k的差值在preSum中出现过，则说明存在一个子数组的和为k
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i <= nums.length; i++) {
            if (map.containsKey(preSum[i] - k)) {
                count += map.get(preSum[i] - k);
            }
            map.put(preSum[i], map.getOrDefault(preSum[i], 0) + 1);
        }
        return count;
    }
}
